//
//  DYYuyueMenpiaoCell.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/5.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit

class DYYuyueMenpiaoCell: SYBaseCell , UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var models: [DYJQYuyuePeopleListModel] = []
    var selectModels: [DYJQYuyuePeopleListModel] = [] {
        didSet {
            let ids = selectModels.map { $0.id }
            self.passParamsClosure?(ids)
        }
    }
    var selectIndexs: [Int] = []
    var tableView: UITableView!
    var collectionView: UICollectionView!
    var bgView: UIView = {
        let v: UIView = UIView()
        v.backgroundColor = UIColor(hex: 0x367FF6)
        v.layer.cornerRadius = 2
        return v
    }()
    
    let nameLb: UILabel = {
        let v:UILabel = UILabel()
        v.textColor = UIColor(hex: 0x1E1E1E)
        v.font = 17.autoBoldFontSize()
        v.text = "游客信息"
        return v
    }()

    public func configureView(_ models: [DYJQYuyuePeopleListModel]) {
        self.models = models
        self.collectionView.reloadData()
        let hang: Double = Double(self.models.count/3+1)
        collectionView.snp.remakeConstraints { (make) in
            make.top.equalTo(nameLb.snp.bottom).offset(autoWidth(14.0))
            make.left.equalToSuperview().offset(15.0.autoWidth())
            make.right.equalToSuperview().offset(-15.0.autoWidth())
            make.height.equalTo((58.0*hang).autoWidth() - 10.autoWidth())
        }
    }
    
    override func initViews() {
        setCollectionView()
        contentView.addSubview(collectionView)
        setTableView()
        contentView.addSubview(nameLb)
        contentView.addSubview(bgView)
        contentView.addSubview(tableView)
        bgView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(16.0.autoWidth())
            make.left.equalToSuperview().offset(autoWidth(14.5))
            make.width.equalTo(4.0.autoWidth())
            make.height.equalTo(15.0.autoWidth())
        }
        nameLb.snp.makeConstraints { (make) in
            make.centerY.equalTo(bgView)
            make.left.equalTo(bgView.snp.right).offset(autoWidth(7.0))
            make.right.equalToSuperview().offset(autoWidth(-15.0))
            make.height.equalTo(16.0.autoWidth())
        }
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(nameLb.snp.bottom).offset(autoWidth(14.0))
            make.left.equalToSuperview().offset(15.0.autoWidth())
            make.right.equalToSuperview().offset(-15.0.autoWidth())
            make.height.equalTo(48.0.autoWidth())
        }
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(collectionView.snp.bottom).offset(autoWidth(15.0))
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 88.autoWidth()), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.isScrollEnabled = false
        self.tableView!.register(DYYoukeInfoCell.self, forCellReuseIdentifier: "Cell")
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return selectModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: DYYoukeInfoCell? = tableView.dequeueReusableCell(withIdentifier: "Cell") as? DYYoukeInfoCell
        cell?.selectionStyle = .none
        cell?.configureView(self.selectModels[indexPath.row])
        cell?.clickedClosure = {[weak self] index in
            if let `self` = self {
                if index == 0 {
                    self.showDeleteAlert(indexPath)
                    
                } else {
                    let vc = DYAddYoukeViewController(type: .edit, model: self.selectModels[indexPath.row])
                    vc.backClosure = {[weak self] index in
                        if let `self` = self {
                            (self.currentVC as! DYYuYueViewController).refreshPeoples()
                        }
                    }
                    self.currentVC.pushVC(vc)
                }
            }
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func setCollectionView() {
        
            
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        let itemWidth = 108.0.autoWidth()
        layout.itemSize = CGSize(width: itemWidth, height: 48.0.autoWidth())
        layout.minimumLineSpacing = 10
//        layout.minimumInteritemSpacing = 10
        layout.scrollDirection = .vertical
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DYYoukeCell.self, forCellWithReuseIdentifier: NSStringFromClass(DYYoukeCell.self))
        self.addSubview(self.collectionView)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.models.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: DYYoukeCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYYoukeCell.self), for: indexPath) as? DYYoukeCell
        
        if indexPath.row == self.models.count {
            cell?.configureView(true)
            cell?.isXuanzhong = false
        } else {
            cell?.configureView(false, self.models[indexPath.row])
            
            if selectModels.count != 0 {
                
                let sames = self.selectModels.filter { $0.id == self.models[indexPath.row].id }
                if sames.count != 0 {
                    cell?.isXuanzhong = true
                    selectIndexs.append(indexPath.row)
                } else {
                    cell?.isXuanzhong = false
                }
                if indexPath.row == self.models.count - 1 {
                    
                    selectModels.removeAll()
                    selectIndexs.forEach { (index) in
                        selectModels.append(self.models[index])
                    }
                    self.tableView.reloadData()
                }
            }
        }
        
        
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell: DYYoukeCell = collectionView.cellForItem(at: indexPath) as! DYYoukeCell
        
        if indexPath.row == self.models.count {
            let vc = DYAddYoukeViewController()
            vc.backClosure = {[weak self] index in
                if let `self` = self {
                    (self.currentVC as! DYYuYueViewController).refreshPeoples()
                }
            }
            self.currentVC.sy_push(vc)
        } else {
            if selectIndexs.count == 0 {
                cell.isXuanzhong = true
                selectIndexs.append(indexPath.row)
            } else {
                
                let sames = selectIndexs.filter { $0 == indexPath.row }
                if sames.count == 0 {
                    cell.isXuanzhong = true
                    selectIndexs.append(indexPath.row)
                } else {
                    cell.isXuanzhong = false
                    selectIndexs = selectIndexs.filter { $0 != indexPath.row }
                }
            }
            
            // MARK: - 排序
            selectIndexs = selectIndexs.sorted{ $0 < $1 }
            selectModels.removeAll()
            selectIndexs.forEach { (index) in
                selectModels.append(self.models[index])
            }
            self.tableView.reloadData()
            tableView.snp.updateConstraints { (make) in
                make.top.equalTo(collectionView.snp.bottom).offset(autoWidth(15.0))
                make.left.right.equalToSuperview()
                make.height.equalTo(130.0.autoWidth()*CGFloat(self.selectModels.count))
                make.bottom.equalToSuperview()
            }
            (self.currentVC as! DYYuYueViewController).tableView.beginUpdates()
            (self.currentVC as! DYYuYueViewController).tableView.endUpdates()
        }
        
    }
    
    func showDeleteAlert(_ indexPath: IndexPath) {
        let alert = PYDeleteAlert()
        alert.clickedClosure = { [weak self] index in
            if let `self` = self {
                if index == 1 {
                    self.collectionView(self.collectionView, didSelectItemAt: indexPath)
                    self.selectIndexs.removeAll()
                    
                    let id = self.models[indexPath.row].id ?? ""
                    (self.currentVC as! DYYuYueViewController).deletePeople(id: id)
                }
            }
            
        }
        let window = UIApplication.shared.keyWindow
        window?.addSubview(alert)
        alert.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
}




// MARK: -DYYuyueTimeSubCell

class DYYoukeCell: SYBaseCollectionViewCell {
    
    var isXuanzhong: Bool = false {
        didSet {
            if isXuanzhong {
                self.pic.image = UIImage(named: "people_kuang")
                self.select.isHidden = false
            } else {
                self.pic.image = UIImage(named: "kuang")
                self.select.isHidden = true
            }
        }
    }
    
    let timeLb: UILabel = {
        let v:UILabel = UILabel()
        v.textColor = UIColor(hex: 0x333333)
        v.font = 16.autoFontSize()
        v.textAlignment = .center
        return v
    }()
    
    let pic: UIImageView = {
        let v: UIImageView = UIImageView()
        v.image = UIImage(named: "kuang")
        v.layer.cornerRadius = 5
        v.clipsToBounds = true
        return v
    }()
    
    let select: UIImageView = {
        let v: UIImageView = UIImageView()
        v.image = UIImage(named: "people_select")
        v.layer.cornerRadius = 5
        v.clipsToBounds = true
        v.isHidden = true
        return v
    }()
    
    var moreBgView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xE6F1FF)
        return v
    }()
    
    let arrow: UIImageView = {
        let v: UIImageView = UIImageView()
        v.image = UIImage(named: "people_arrow")
        return v
    }()
    

    public func configureView(_ isLast: Bool, _ model: DYJQYuyuePeopleListModel? = nil) {
        if isLast {
            self.moreBgView.isHidden = false
            self.arrow.isHidden = false
            timeLb.text = "  新增/更换"
            timeLb.textAlignment = .left
        } else {
            self.moreBgView.isHidden = true
            self.arrow.isHidden = true
            timeLb.text = model?.name
            timeLb.textAlignment = .center
        }
    }
    
    
    
    override func initViews() {
        
        
        addSubview(pic)
        addSubview(timeLb)
        pic.addSubview(moreBgView)
        addSubview(arrow)
        addSubview(select)
        timeLb.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.right.left.equalToSuperview()
            make.height.equalTo(15.0.autoWidth())
            
        }
        pic.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
        }
        
        moreBgView.snp.makeConstraints { (make) in
            make.centerY.equalTo(pic)
            make.right.equalTo(pic)
            make.height.equalTo(48.0.autoWidth())
            make.width.equalTo(17.0.autoWidth())
        }
        arrow.snp.makeConstraints { (make) in
            make.centerY.equalTo(pic)
            make.right.equalTo(pic.snp.right).offset(autoWidth(-4.0))
            make.width.equalTo(6.0.autoWidth())
            make.height.equalTo(12.0.autoWidth())
        }
        select.snp.makeConstraints { (make) in
            make.bottom.right.equalTo(pic)
            make.width.equalTo(18.0.autoWidth())
            make.height.equalTo(12.0.autoWidth())
        }
    }
}

